﻿#include <QThread>
#include <QEventLoop>
#include <QTimer>
#include <QNetworkReply>
#include "CImgDownloadTh.h"

CImgDownloadTh::CImgDownloadTh(QObject *parent)
	: QThread(parent),
	m_networkManager(new QNetworkAccessManager(this))
{
	// 设置为后台线程
	setTerminationEnabled(true);
	m_bIsFrist = false;
	start();
}

CImgDownloadTh::~CImgDownloadTh()
{
	delete m_networkManager;
}

CImgDownloadTh *CImgDownloadTh::instance()
{
	static CImgDownloadTh *instance = nullptr;
	if (!instance)
	{
		instance = new CImgDownloadTh();
	}
	return instance;
}

void CImgDownloadTh::addRequest(const QUrl &url, QLabel *label,QString sPageUuid)
{
	QMutexLocker locker(&m_queueMutex);  // 加锁
	m_sPageUuid = sPageUuid;
	m_requestQueue.enqueue(qMakePair(url, label));  // 将请求加入队列
}

void CImgDownloadTh::addRequest(QQueue<QPair<QUrl, QLabel*>> pairRequest, QString sPageUuid)
{
	QMutexLocker locker(&m_queueMutex);  // 加锁
	m_sPageUuid = sPageUuid;
	m_bIsFrist = false;
	m_requestQueue.clear();
	m_requestQueue.append(pairRequest);
}

void CImgDownloadTh::clearRequest()
{
	QMutexLocker locker(&m_queueMutex);  // 加锁
	m_requestQueue.clear();
	m_sPageUuid = "";
}

void CImgDownloadTh::run()
{
	while (true)
	{
		QPair<QUrl, QLabel*> request;
		bool bFind = false;
		{
			QMutexLocker locker(&m_queueMutex);  // 加锁

		// 如果队列为空，等待有新的请求
			if (m_requestQueue.isEmpty())
			{
				//m_condition.wait(&m_queueMutex);//标记
				QEventLoop loop;
				QTimer::singleShot(100, &loop, SLOT(quit()));
				loop.exec();
				continue;
			}

			// 获取队列中的下一个请求
			request = m_requestQueue.dequeue();
			bFind = true;
		}
		
		if (false == bFind) continue;

		// 下载图片
		downloadImage(request.first, request.second);

		QEventLoop loop;
		QTimer::singleShot(5, &loop, SLOT(quit()));//一秒钟查询一下数据库
		loop.exec();
	}
}

void CImgDownloadTh::downloadImage(const QUrl &url, QLabel *label)
{
	// 创建请求
	QNetworkRequest request(url);

	// 下载图片
	QNetworkReply *reply = m_networkManager->get(request);
	QTimer::singleShot(5000, reply, &QNetworkReply::abort); // 设置5秒超时
	// 等待下载完成
	QEventLoop eventLoop;
	connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
	eventLoop.exec();

	// 处理下载结果
	if (reply->error() == QNetworkReply::NoError)
	{
		QByteArray data = reply->readAll();
		QImage image;
		image.loadFromData(data);

		if (!image.isNull()) 
		{
			// 图片下载成功，更新界面
			QPixmap pixmap = QPixmap::fromImage(image);
			QMutexLocker locker(&m_queueMutex);  // 加锁
			if (!m_bIsFrist)
			{
				m_bIsFrist = true;
				m_sOldPageUuid = m_sPageUuid;
				emit imageDownloaded(label, pixmap,m_sPageUuid);
			}
			else
			{
				if (m_sOldPageUuid == m_sPageUuid)
				{
					emit imageDownloaded(label, pixmap, m_sPageUuid);
				}
				else
				{
					m_sOldPageUuid = m_sPageUuid;
				}
			}
		}
		else 
		{
			qWarning() << "Failed to load image from data.";
		}
	}
	else 
	{
		qWarning() << "Download failed:" << reply->errorString();
	}

	// 清理
	reply->deleteLater();
}
